<template>
	<div class="container">
    <PageTitle />
		<!-- content -->
		<el-row :gutter="20">
			<!-- tree -->
			<el-col :span="6">
				<div class="tree" v-loading="treeLoading">
					<el-button type="primary" size="mini" icon="el-icon-plus" class="add-plat-btn" @click="addPlat">
						添加平台
					</el-button>
					<el-button :loading="exportLoading" type="primary" size="mini" icon="el-icon-upload2" class="add-plat-btn" @click="exportElement(0)">
						导出元素
					</el-button>
					<el-tree
							:data="data"
							node-key="pkId"
							default-expand-all
							:current-node-key="currentId"
							:expand-on-click-node="false"
							ref="tree"
					>
						<div class="custom-tree-node" slot-scope="{ node, data }" @click="recordCurrentId(data)">
							<span class="txt" @click="look (node, data)">{{ data.name }}</span>
							<span v-if="isHaveAdd(node, data)" @click="append(node, data)"
								  class="tree-btn tree-btn-add">
									<i class="el-icon-plus"/>
							</span>
							<span v-if="data.name != '权限菜单' && data.name != '角色' && data.dataType != 'role'" @click="edit(node, data)"
									  class="tree-btn tree-btn-edit">
								<i class="el-icon-edit-outline"/>
							</span>
							<span v-if="data.name != '权限菜单' && data.name != '角色' && data.dataType != 'role'" @click="remove(node, data)"
									  class="tree-btn tree-btn-remove">
								<i class="el-icon-delete"/>
							</span>
							<span v-if="data.permissionLeaf == 1" @click="exportElement(1,node, data)"
								  class="tree-btn tree-btn-download">
								<i class="el-icon-download"/>
							</span>
						</div>
					</el-tree>
				</div>
			</el-col>
			<!-- tree end -->

			<!-- single-element -->
			<el-col :span="18" v-if="addElment == 0" v-loading="addElementLoading">
				<div class="single-element" style="background: #fff">
					<el-button type="primary" size="mini"  @click="insertElement">添加元素</el-button>
					<div class="element-tag-box">
						<el-tag
								:key="item.elementId"
								v-for="item in singleList"
								closable
								:disable-transitions="false"
								@close="elementDelete(item)"
								class="element-tag"
						>
							{{item.elementName}}
						</el-tag>
					</div>
				</div>
			</el-col>
			<!-- single-element end -->
			<!-- multiple-element end -->
			<el-col :span="18" v-if="addElment == 1" class="multiple-element"  v-loading="addElementLoading">
				<el-tabs
						type="border-card"
						editable
						@edit="tabsEdit"
						class="tabs"
						v-model="element.elementParentId"
						style="min-height: 400px;"
				>
					<el-tab-pane
							v-for="item in multipleList || []"
							:name="item.elementId"
							:label="item.elementName"
					>
						<el-button type="primary" size="mini" @click="insertElement(item.elementId)">添加元素</el-button>
						<div class="element-tag-box">
							<el-tag
									:key="sitem.elementAclId"
									v-for="sitem in item.elementChildList"
									closable
									:disable-transitions="false"
									@close="elementDelete(sitem)"
									class="element-tag"
							>
								{{sitem.elementName}}
							</el-tag>
						</div>
					</el-tab-pane>
				</el-tabs>
			</el-col>
			<!-- multiple-element end -->
			<!-- select-tree -->
			<el-col :span="6" v-if="selectPermission.visible">
				<div class="tree" v-loading="selectPermission.loading">
					<el-tree
							:data="selectPermission.data"
							node-key="id"
							default-expand-all
							:expand-on-click-node="false"
							show-checkbox
							ref="selectTree"
							:props="{chidlren: 'children',label: 'name'}"
					/>
					<div style="text-align: right">
						<el-button type="primary" size="mini" @click="saveRoleSelect">保存</el-button>
						<el-button size="mini" @click="resetRoleSelect">重置</el-button>
					</div>
				</div>
			</el-col>
			<!-- select-tree end -->
		</el-row>
		<!-- content end -->

		<!-- plat -->
		<el-dialog
				:title="plat.title"
				:visible.sync="plat.visible"
				width="40%"
				:close-on-click-modal="false"
				@close="closeDialog(0)"
		>
			<bc-form
					:model="plat.data"
					:element="plat.element"
					element-name="platForm"
					label-width="80px"
					ref="platForm"
			/>
			<div slot="footer" class="dialog-footer">
				<el-button @click="plat.visible = false">取 消</el-button>
				<el-button type="primary" :loading="plat.loading" @click="handleSubmit(0)">确 定</el-button>
			</div>
		</el-dialog>
		<!-- plat end -->

		<!-- permission -->
		<el-dialog
				:title="permission.title"
				:visible.sync="permission.visible"
				width="40%"
				class="addMenuDialog"
				:close-on-click-modal="false"
				@close="closeDialog(1)"
		>
			<bc-form
					:model="permission.data"
					:element="permission.element"
					element-name="permissionForm"
					label-width="250px"
					ref="permissionForm"
			/>
			<div slot="footer" class="dialog-footer">
				<el-button @click="permission.visible = false">取 消</el-button>
				<el-button type="primary" :loading="permission.loading" @click="handleSubmit(1)">确 定</el-button>
			</div>
		</el-dialog>
		<!-- permission end -->

		<!-- role -->
		<el-dialog
				:title="role.title"
				:visible.sync="role.visible"
				width="40%"
				:close-on-click-modal="false"
				@close="closeDialog(2)"
		>
			<bc-form
					:model="role.data"
					:element="role.element"
					element-name="roleForm"
					label-width="80px"
					ref="roleForm"
			/>
			<div slot="footer" class="dialog-footer">
				<el-button @click="role.visible = false">取 消</el-button>
				<el-button type="primary" :loading="role.loading" @click="handleSubmit(2)">确 定</el-button>
			</div>
		</el-dialog>
		<!-- role end -->

		<!-- element -->
		<el-dialog
				:title="element.title"
				:visible.sync="element.visible"
				width="40%"
				:close-on-click-modal="false"
				@close="closeDialog(3)"
		>
			<el-form
					:model="element.data"
					label-width="100px"
					label-suffix=":"
					size="small"
					ref="elementForm"
					class="element-form"
					style="padding: 0 20px"
			>
				<el-form-item
						v-for="(item, index) in element.data.domains"
						label="元素名称"
						:key="index"
						:prop="'domains.' + index + '.elementName'"
						:rules="{required: true, message: '请输入元素名称', trigger: 'blur'}"
						class="form-item"
				>
					<el-input v-model="item.elementName" placeholder="请输入元素名称"/>
					<el-button v-if="index == 0" icon="el-icon-plus" circle class="circlr-btn"
							   @click="addElmentItem"></el-button>
					<el-button v-else icon="el-icon-delete" circle class="circlr-btn"
							   @click="deleteElmentItem(index)"></el-button>
				</el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click="element.visible = false">取 消</el-button>
				<el-button type="primary" :loading="element.loading" @click="handleSubmit(3)">确 定</el-button>
			</div>
		</el-dialog>
		<!-- element end -->

	</div>
</template>

<script>
    import {bcSubmitAlert} from '@/utils/bc-form-data';
    import {
      getTree,
      insertPlat,
      updatePlat,
      detailPlat,
      deletePlat,
      insertPermission,
      updatePermission,
      detailPermission,
      deletePermission,
      insertRole,
      updateRole,
      detailRole,
      deleteRole,
      insertElements,
      deleteElement,
      getElements,
      getTreeByRole,
      saveRolePermission,
      getAllElementsList, getTreeNew
    } from '@/api/system/permission/index'
    import {buildTree} from '@/utils/toolkit';
    import BcForm from '@/components/BcForm';
	  import { BcExportExcel } from '@/vendor/BcExportExcel'
    import PageTitle from "@/components/PageTitle/index";

    export default {
        name: 'Permission',
        components: {
            BcForm,PageTitle
        },
        data() {
            return {
                exportLoading: false,
                data: [], // 树
                addElment: -1, // 0 单页面 1 多页面
				addElementLoading: false, // 元素
                treeLoading: false, // 树
				currentId: '', // 树激活id
				currentPlatId: '', // 当前品台id
				currentPermissionLayout: '', // 元素所属菜单类型
                plat: { // 平台
                    visible: false,
                    title: '添加平台',
                    state: 'insert',
                    loading: false,
                    element: [
                        {
                            label: '平台名称',
                            key: 'projectName',
                            type: 'input',
                            required: true
                        },
                        {
                            label: '平台描述',
                            key: 'projectDesc',
                            type: 'textarea'
                        }
                    ],
                    data: {
                        projectId: '',
                        projectName: '',
                        projectDesc: ''
                    }
                },
                permission: { // 权限菜单
                    visible: false,
                    title: '添加权限菜单',
                    state: 'insert',
                    loading: false,
                    element: [
                        {
                            label: '菜单名称(title)',
                            key: 'permissionName',
                            type: 'input',
                            required: true
                        },
                        {
                            label: '路径(path)',
                            key: 'permissionUrl',
                            type: 'input',
                            required: true
                        },
                        {
                            label: '组件名称(name)',
                            key: 'permissionComponentName',
                            type: 'input',
                            required: true
                        },
                        {
                            label: '组件路径(component)',
                            key: 'permissionComponent',
                            type: 'input',
                            required: true
                        },
                        {
                            label: '重定向路径(redirect)',
                            key: 'permissionRedirect',
                            type: 'input'
                        },
                        {
                            label: '图标(icon)',
                            key: 'permissionIcon',
                            type: 'input'
                        },
                        {
                            label: '排序',
                            key: 'permissionOrder',
                            type: 'int',
                            required: true
                        }, {
                            label: '是否隐藏(hidden)',
                            key: 'permissionHidden',
                            type: 'radio',
                            required: true,
                            list: [
                                {
                                    label: '是',
                                    value: '0'
                                }, {
                                    label: '否',
                                    value: '1'
                                }
                            ]
                        }, {
                            label: '是否取消缓存(nocache)',
                            key: 'permissionNoCache',
                            type: 'radio',
                            required: true,
                            list: [
                                {
                                    label: '是',
                                    value: '0'
                                }, {
                                    label: '否',
                                    value: '1'
                                }
                            ]
                        }, {
                            label: '是否固定tags-view(affix)',
                            key: 'permissionAffix',
                            type: 'radio',
                            required: true,
                            list: [
                                {
                                    label: '是',
                                    value: '0'
                                }, {
                                    label: '否',
                                    value: '1'
                                }
                            ]
                        }, {
                            label: '是否强制显示跟路由(alwaysShow)',
                            key: 'permissionAlwaysShow',
                            type: 'radio',
                            required: true,
                            list: [
                                {
                                    label: '是',
                                    value: '0'
                                }, {
                                    label: '否',
                                    value: '1'
                                }
                            ]
                        },
                        {
                            label: '是否有叶子节点',
                            key: 'permissionLeaf',
                            type: 'radio',
                            required: true,
                            disabled: false,
                            list: [
                                {
                                    label: '是',
                                    value: '0'
                                }, {
                                    label: '否',
                                    value: '1'
                                }
                            ]
                        }, {
                            label: '菜单类型',
                            key: 'permissionLayout',
                            type: 'radio',
                            required: true,
                            list: [
                                {
                                    label: '单页',
                                    value: '0'
                                }, {
                                    label: '多tab页',
                                    value: '1'
                                }
                            ]
                        },
                        {
                            label: '高亮菜单路径(activeMenu)',
                            key: 'permissionActiveMenu',
                            type: 'input'
                        }, {
                            label: '菜单描述',
                            key: 'permissionDesc',
                            type: 'textarea'
                        }
                    ],
                    data: {
                        permissionId: '',
                        projectId: '',
                        permissionName: '',
                        permissionDesc: '',
                        permissionUrl: '',
                        permissionParentId: '',
                        permissionOrder: '',
                        permissionLeaf: '0',
                        permissionLayout: '0',
                        permissionComponentName: '',
                        permissionComponent: '',
                        permissionRedirect: '',
                        permissionIcon: '',
                        permissionHidden: '1',
                        permissionNoCache: '1',
                        permissionAffix: '1',
                        permissionAlwaysShow: '1',
                        permissionActiveMenu: ''
                    }
                },
                role: { // 角色
                    title: '添加角色',
                    visible: false,
                    state: 'insert',
                    loading: false,
                    element: [
                        {
                            label: '角色名称',
                            key: 'roleName',
                            type: 'input',
                            required: true
                        },
                        {
                            label: '是否锁定',
                            key: 'roleIsLock',
                            type: 'radio',
                            required: true,
                            list: [
                                {
                                    label: '是',
                                    value: 1
                                }, {
                                    label: '否',
                                    value: 0
                                }
                            ]
                        },
                        {
                            label: '角色描述',
                            key: 'roleDesc',
                            type: 'textarea'
                        }
                    ],
                    data: {
                        roleId: '',
                        projectId: '',
                        roleName: '',
                        roleDesc: '',
                        roleIsLock: 0
                    }
                },
                element: { // 元素
                    title: '添加元素',
                    visible: false,
                    state: 'insert',
                    loading: false,
                    permissionId: '',
                    elementParentId: '',
					currentTabId: '',
                    data: {
                        domains: [{
                            permissionId: '',
                            elementName: '',
                            elementParentId: ''
                        }]
                    }
                },
                singleList: [], // 单页面元素列表
                multipleList: [], // 多tab页面元素列表
                selectPermission: { // 选择权限菜单
                    visible: false,
					loading: false,
					currentId: '',
					data: []
				},
				checkThePath: function(level) {
	                  let regExp = /^\/.*/
	                    return function(rule, value, callback) {
							if(value == ''){
	                          callback(new Error('请输入路径'))
							} else {
                              if(!regExp.test(value) && level === 0){
                                  callback(new Error('一级菜单路径需以“/”开头'))
                                return
                              } else if(regExp.test(value) && level !== 0){
                                callback(new Error('一级菜单路径除外，其他级别路径不能以“/”开头'))
                                return
                              } else {
                                callback()
                              }
							}
	                    }
	              },
              checkTheComponentPath: function(level) {
                let regExp = /^@.*/
                return function(rule, value, callback) {
                  if(value == ''){
                    callback(new Error('请输入路径'))
                  } else {
                    if(value !== 'Layout' && level === 0){
                      callback(new Error('一级菜单的组件路径为Layout'))
                      return
                    } else if(!regExp.test(value) && level !== 0){
                      callback(new Error('一级菜单外，其他级别组件路径需以@开头'))
                      return
                    } else {
                      callback()
                    }
                  }
                }
              },

            };
        },
        created() {
            this.getTree();
        },
        methods: {
            // 获取树左侧树数据
            getTree() {
                this.treeLoading = true
              getTreeNew({}).then(res => {
                    if (res.data) {
                      let permissonData = res.data.filter(item=>
                        item.dataType!=='role')
                        this.data = buildTree(permissonData, {
                            parentId: 'pid',
                            id: 'id'
                        });
                    }
					this.$nextTick(() => {
                        this.$refs.tree.setCurrentKey(+this.currentId || null)
					})
                    this.treeLoading = false
                }).catch(err => {
                    this.treeLoading = false
				});

            },

            // 判断是否有加号按钮
            isHaveAdd(node, data) {
                let arr = ['权限菜单'];
                if (arr.includes(data.name)) {
                    return true;
                } else if (node.level > 1 && data.permissionLeaf == '0') {
                    return true;
                }
                return false;
            },

			// 树当前激活id
            recordCurrentId(data){
                this.currentId = +data.pkId
			},

            // 添加平台
            addPlat() {
                this.plat.visible = true;
                this.plat.state = 'insert';
            },

            // 树-新增
            append(node, data) {
                if(this.currentId != data.pkId){
                    this.selectPermission.visible = false
                    this.addElment = -1
                }
                switch (node.level) {
                    case 1:
                        break;
                    case 2:
                        // 添加权限菜单或角色
                        if (data.name == '权限菜单') {
                            // 一级菜单
                            this.permission.element[11].disabled = true;
                            this.permission.element[12].disabled = false;
                            // 修改路径验证规则
                            this.permission.element[1].rules = this.checkThePath(0)
                            this.permission.element[3].rules = this.checkTheComponentPath(0)
                            this.permission.data.projectId = data.projectId;
                            // this.permission.data.permissionParentId = data.pkId;
                            this.permission.data.permissionParentId = -1;
                            this.permission.visible = true;
                          this.$nextTick(() => {
                            this.$refs.permissionForm.dealRules()
                          })
                            this.permission.state = 'insert';
                        } else {
                            // 角色
                            this.role.data.projectId = data.projectId;
                            this.role.visible = true;
                            this.role.state = 'insert';
                        }
                        break;
                    default:
                        // 添加菜单
                        this.permission.element[10].disabled = false;
                        this.permission.element[11].disabled = false;
                        // 修改路径验证规则
                        this.permission.element[1].rules = this.checkThePath()
                        this.permission.element[3].rules = this.checkTheComponentPath()
                        this.permission.data.projectId = data.projectId;
                        this.permission.data.permissionParentId = data.pkId;
                        this.permission.visible = true;
                      this.$nextTick(() => {
                        this.$refs.permissionForm.dealRules()
                      })
                        this.permission.state = 'insert';
                }
            },

            // 树-查看
            look(node, data) {
                if(this.currentId != data.pkId){
                    this.selectPermission.visible = false
                    this.addElment = -1
                }
                if(node.level > 2){
                    switch(data.dataType){
                        case 'permission':
                            // 元素
							if(data.permissionLeaf == 1){
                                this.addElment = data.permissionLayout;
                                this.currentPermissionLayout = data.permissionLayout
                                this.addElementLoading = true
                                this.getElements(data.pkId, data.permissionLayout,'init')
                                this.selectPermission.visible = false
							}
                            break;
                        case 'role':
                            // 角色
							this.selectPermission.loading = true
                            this.selectPermission.visible = true
                            this.addElment = -1;
							this.rebackRoleSelect(data.projectId, data.pkId)
                            this.currentId = data.pkId
                            this.currentPlatId = data.projectId
                            break;
                    }
				}
            },

            // 树-修改
            edit(node, data) {
                if(this.currentId != data.pkId){
                    this.selectPermission.visible = false
                    this.addElment = -1
                }
                switch (node.level) {
                    case 1:
                        // 修改平台
                        bcSubmitAlert(detailPlat, {id: data.pkId}, true).then(res => {
                            this.plat.data = res.data;
                            this.plat.state = 'update';
                            this.plat.visible = true;
                        });
                        break;
                    case 3:
                        if (data.dataType == 'permission') {
                            // 修改菜单
                            bcSubmitAlert(detailPermission, {id: data.pkId}, true).then(res => {
	                            res.data.children = []
                                this.permission.element[11].disabled = true;
                                this.permission.element[12].disabled = true;
                                // 修改路径验证规则
                                this.permission.element[1].rules = this.checkThePath(0)
                                this.permission.element[3].rules = this.checkTheComponentPath(0)
                                this.permission.data = res.data;
                                this.permission.state = 'update';
                                this.permission.visible = true;
	                              this.$nextTick(() => {
	                                this.$refs.permissionForm.dealRules()
	                              })
                            });
                        }
                        if (data.dataType == 'role') {
                            bcSubmitAlert(detailRole, {id: data.pkId}, true).then(res => {
                                this.role.data = res.data;
                                this.role.state = 'update';
                                this.role.visible = true;
                            });
                        }
                        break;
                    default:
                        // 修改菜单
                        bcSubmitAlert(detailPermission, {id: data.pkId}, true).then(res => {
                            res.data.children = []
                            this.permission.element[11].disabled = true;
                            this.permission.element[12].disabled = true;
                            // 修改路径验证规则
                            this.permission.element[1].rules = this.checkThePath()
                            this.permission.element[3].rules = this.checkTheComponentPath()
                            this.permission.data = res.data;
                            this.permission.state = 'update';
                            this.permission.visible = true;
                            this.$nextTick(() => {
                              this.$refs.permissionForm.dealRules()
                            })
                        });
                }
            },

            // 树-删除
            remove(node, data) {
                if(this.currentId != data.pkId){
                    this.selectPermission.visible = false
                    this.addElment = -1
				}
                if (node.childNodes && node.childNodes.length > 0 && node.level != 1) {
                    this.$message.warning('当前节点存在子节点，不可删除')
                    return;
                }
                if(node.level == 1 && (node.childNodes[0].childNodes.length != 0 || node.childNodes[1].childNodes.length != 0)){
                    this.$message.warning('当前节点存在子节点，不可删除')
                    return;
				}
                getElements({permissionId: data.pkId}).then(res => {
					if(res.data.length > 0){
                        this.$message.warning('当前节点存在子元素，不可删除')
					} else {
                        this.$confirm('确认删除该项?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            switch (node.level) {
                                case 1:
                                    // 删除平台
                                    bcSubmitAlert(deletePlat, {id: data.pkId}).then(() => {
                                        this.getTree();
                                    });
                                    break;
                                case 2:
                                    // 删除权限菜单或角色
                                    if (data.name == '权限菜单') {
                                        // 删除菜单
                                        bcSubmitAlert(deletePermission, {id: data.pkId}).then(() => {
                                            this.getTree();
                                        });
                                    } else {
                                        // 删除角色
                                        bcSubmitAlert(deleteRole, {id: data.pkId}).then(() => {
                                            this.getTree();
                                        });
                                    }
                                    break;
                                default:
                                    if (data.dataType == 'role') {
                                        // 删除角色
                                        bcSubmitAlert(deleteRole, {id: data.pkId}).then(() => {
                                            this.getTree();
                                        });
                                    } else {
                                        // 删除菜单
                                        bcSubmitAlert(deletePermission, {id: data.pkId}).then(() => {
                                            this.getTree();
                                        });
                                    }
                            }
                        }).catch(err => {

                        });
					}
				}).catch(err => {
				    this.$message.error('查询子元素信息失败')
				})
            },

            // 表单提交
            handleSubmit(type) {
                switch (type) {
                    case 0:
                        this.$refs.platForm.submit().then(data => {
                            // 平台
                            this.plat.loading = true;
                            if (this.plat.state == 'insert') {
                                // 新增
                                this.submitData(insertPlat, data, 0);
                            } else {
                                // 修改
                                this.submitData(updatePlat, data, 0);
                            }
                        });
                        break;
                    case 1:
                        this.$refs.permissionForm.submit().then(data => {
                            // 权限菜单
                            this.permission.loading = true;
                            if (this.permission.state == 'insert') {
                                // 新增
                                this.submitData(insertPermission, data, 1);
                            } else {
                                // 修改
                                this.submitData(updatePermission, data, 1);
                            }
                        });
                        break;
                    case 2:
                        this.$refs.roleForm.submit().then(data => {
                            // 角色
                            this.role.loading = true;
                            if (this.role.state == 'insert') {
                                // 新增
                                this.submitData(insertRole, data, 2);
                            } else {
                                // 修改
                                this.submitData(updateRole, data, 2);
                            }
                        });
                        break;
                    case 3:
                        this.$confirm('请确认表单内容填写正确，元素添加之后将不可修改！', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            this.$refs.elementForm.validate(valid => {
                                if (valid) {
                                    this.element.data.domains[0].permissionId = this.element.permissionId
                                    this.element.data.domains[0].elementParentId = this.element.elementParentId || ''
                                    // 元素
                                    this.element.loading = true;
                                    if (this.element.state == 'insert') {
                                        // 新增
										this.submitData(insertElements, JSON.stringify(this.element.data.domains), 3);
                                    } else {
                                        // 修改
                                    }
                                }

                            });
                        }).catch(err => {

                        })
                        break;
                }
            },

            // 数据提交
            submitData(method, data, type) {
                method(data).then(res => {
                    if (res.data.flag) {
                        this.submitAfter(res.data.message, 'success', type);
                    } else {
                        this.submitAfter(res.data.message, 'fail', type, true);
                    }
                }).catch(err => {
                    this.submitAfter('', 'fail', type);
                });
            },

            // 提交之后
            submitAfter(message, state, type, nohidden = false) {
                if (state == 'success') {
                    this.$notify({
                        title: '成功',
                        message: message || '操作成功',
                        type: 'success'
                    });
                    this.getTree();
                } else {
                    this.$message.error(message || '操作失败');
                }
                switch (type) {
                    case 0:
                        this.plat.loading = false;
                        break;
                    case 1:
                        this.permission.loading = false;
                        break;
                    case 2:
                        this.role.loading = false;
                        break;
                    case 3:
                        this.element.loading = false;
                        this.getTree()
                        this.getElements(this.currentId,this.currentPermissionLayout)
                        break;
                }
                if (!nohidden) {
                    switch (type) {
                        case 0:
                            this.plat.visible = false;
                            break;
                        case 1:
                            this.permission.visible = false;
                            break;
                        case 2:
                            this.role.visible = false;
                            break;
                        case 3:
                            this.element.visible = false;
                            break;
                    }
                }
            },

            // 关闭弹窗
            closeDialog(type) {
                switch (type) {
                    case 0:
                        this.plat.loading = false
                        this.plat.data = {
                            projectId: '',
                            projectName: '',
                            projectDesc: ''
                        };
                        this.$nextTick(() => {
                            this.$refs.platForm.reset();
						})
                        break;
                    case 1:
                        this.permission.loading = false
                        this.permission.data = {
                            permissionId: '',
                            projectId: '',
                            permissionName: '',
                            permissionDesc: '',
                            permissionUrl: '',
                            permissionParentId: '',
                            permissionOrder: '',
                            permissionLeaf: '0',
                            permissionLayout: '0',
                            permissionComponentName: '',
                            permissionRedirect: '',
                            permissionIcon: '',
                            permissionHidden: '1',
                            permissionNoCache: '1',
                            permissionAffix: '1',
                            permissionAlwaysShow: '1',
                            permissionActiveMenu: ''
                        };
                        this.$nextTick(() => {
                            this.$refs.permissionForm.reset();
                        })
                        break;
                    case 2:
                        this.role.loading = false
                        this.role.data = {
                            roleId: '',
                            projectId: '',
                            roleName: '',
                            roleDesc: '',
                            roleIsLock: 0
                        };
                        this.$nextTick(() => {
                            this.$refs.roleForm.reset();
                        })
                        break;
                    case 3:
                        this.element.loading = false
                        this.element.data.domains = [{
                            permissionId: '',
                            elementName: '',
                            elementParentId: ''
                        }];
                        this.$nextTick(() => {
                            this.$refs.elementForm.clearValidate();
                        })
                        break;

                }
            },

            // 获取元素列表
            getElements(id,permissionLayout,state){
                this.addElementLoading = true
                bcSubmitAlert(getElements,{permissionId: id}, true).then(res => {
                    this.element.permissionId = id;
                    // this.element.elementParentId =  '';
                    if(res.data.length > 0){
                        res.data.map(item => {
                            item.elementId += ''
                            item.elementChildList.map(sitem => {
                                sitem.elementId += ''
                            })
                        })
                        if(permissionLayout == 0){
                            this.singleList = res.data
                            this.element.elementParentId = ''
                        } else {
                            this.multipleList = res.data
							if(state == 'init'){
                                this.element.elementParentId = res.data[0].elementId
							}
                        }
					} else {
                        if(permissionLayout == 0){
                            this.singleList = []
                            this.element.elementParentId = ''
                        } else {
                            this.multipleList = []
                            this.element.elementParentId = ''
                        }
					}
                    this.addElementLoading = false
                })
            },

            // 编辑tab
            tabsEdit(targetName, action) {
                switch (action) {
                    case 'add':
                        // 添加
						this.element.elementParentId = ''
                        this.element.title = '新增tab元素';
                        this.element.visible = true;
                        this.element.state = 'insert';
                        break;
                    case 'remove':
                        this.deleteElement(targetName, true)
                        break;
                }
            },

            // 添加元素
            insertElement(parentId) {
                // 按钮点击默认会传回一个点击事件对像，要判断下类型
                if(parentId && (typeof parentId == 'number' || typeof parentId == 'string')){
                    this.element.elementParentId = parentId
				} else {
                    this.element.elementParentId = ''
				}
                this.element.title = '添加元素'
                this.element.visible = true;
                this.element.state = 'insert';
            },

            // 添加表单项
            addElmentItem() {
                this.element.data.domains.push({
                    elementName: '',
                    permissionId: this.element.permissionId,
                    elementParentId: this.element.elementParentId
                });
            },

            // 删除表单项
            deleteElmentItem(index) {
                this.element.data.domains.splice(index, 1);
            },

            // 删除元素
            elementDelete(data) {
                this.deleteElement(data.elementId)
            },

			// 元素删除
			deleteElement(id, check){
                if(check){
                    let canDelete = true
                    this.multipleList.forEach(item => {
                        if(item.elementId == id && item.elementChildList.length > 0){
                            canDelete = false
                        }
                    })
                    if(!canDelete){
                        this.$message.error('当前元素存在下属元素，不可删除')
                        return
                    }
				}
                this.$confirm('确认删除该项?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    bcSubmitAlert(deleteElement,{id: id}).then(res => {
                        this.getTree()
                        this.getElements(this.currentId,this.currentPermissionLayout)
                    })
                }).catch(err => {

                })
			},

			// 回显菜单
			rebackRoleSelect(projectId, roleId){
                this.selectPermission.currentId = roleId
                this.selectPermission.loading = true
                bcSubmitAlert(getTreeByRole,{
                    projectId: projectId,
                    roleId: roleId
                }, true).then(res =>{
					let arr = []
                    this.selectPermission.data = buildTree(res.data, {
                        parentId: 'pid',
                        id: 'id'
                    });
                    buildCheckedKeys(this.selectPermission.data)
                    this.$refs.selectTree.setCheckedKeys(arr);
					this.selectPermission.loading = false

					function buildCheckedKeys(data) {
						data.forEach(item => {
						    if(item.children && item.children.length > 0){
                                buildCheckedKeys(item.children)
							} else if(item.roleSelect == 1) {
                                arr.push(item.id)
							}
						})
                    }
				})
			},

			// 保存选中的菜单
			saveRoleSelect(){
                let selectArr = this.$refs.selectTree.getCheckedNodes()
                let selectHalfArr = this.$refs.selectTree.getHalfCheckedNodes()
				let data = {
                    roleId: this.selectPermission.currentId,
                    permisionList: [],
                    elementList: []
				}
                selectHalfArr.forEach(item => {
				    if(item.id.split('#')[1] == 'permission'){
                        data.permisionList.push(item.pkId)
					}
                    if(item.id.split('#')[1] == 'permissionElement'){
                        data.elementList.push(item.pkId)
                    }
				})
				selectArr.forEach(item => {
				    if(item.id.split('#')[1] == 'permission'){
                        data.permisionList.push(item.pkId)
					}
                    if(item.id.split('#')[1] == 'permissionElement'){
                        data.elementList.push(item.pkId)
                    }
				})
				bcSubmitAlert(saveRolePermission,JSON.stringify(data)).then(res => {
					this.getTree()
					this.rebackRoleSelect(this.currentPlatId,this.currentId)
					// this.selectPermission.visible = true
				})
			},

			// 重置选中的菜单
            resetRoleSelect(){
                this.$refs.selectTree.setCheckedKeys([]);
			},

			// 导出
            exportElement(type,node, data){
	            if(type == 0){
	                // 导出全部
		            this.exportLoading = true
                    bcSubmitAlert(getAllElementsList,{}, true).then(res => {
                        if(res.data.items.length > 0){
                            let data =  {},
                                routes = {}
                            // id 对应菜单名称
                            buildRoutes(this.$store.getters.routes)
                            // 填充数据
                            res.data.items.forEach(item => {
                                if(!data[routes[item.permissionId]]){
                                    data[routes[item.permissionId]] = [item]
                                } else {
                                    data[routes[item.permissionId]].push(item)
                                }
                            })
                            // 多tab页
                            let sheetData = [],
                                sheetList = []
                            for (const k in data) {
                                let arr = []
                                sheetList.push(k)
                                data[k].forEach(sitem =>{
                                    arr.push({
                                        "元素名称": sitem.elementName,
                                        "Aclid": sitem.elementAclId
                                    })
                                })
                                sheetData.push(arr)
                            }
                            BcExportExcel({sheetData,sheetList,name: data.name})
                            this.exportLoading = false

                            function buildRoutes(list){
                                list.forEach(item => {
                                    if(item.children && item.children.length > 0){
                                        buildRoutes(item.children)
                                    } else {
                                        if(item.meta && item.meta.id && item.meta.title) {
                                            routes[item.meta.id] = item.meta.title
                                        }
                                    }
                                })
                            }
                        } else {
                            this.$message.error('当前没有需要导出的元素')
                            this.exportLoading = false
                        }
                    }).catch(err => {
                        this.exportLoading = false
                    })
	            } else {
                    // 单个菜单元素导出
                    bcSubmitAlert(getElements,{permissionId: data.pkId}, true).then(res => {
                        if(res.data.length > 0){
                            if(data.permissionLayout == 0){
                                // 单页面
                                var sheetData = [[]],
                                    sheetList = [data.name]
                                res.data.forEach((item,index) => {
                                    sheetData[0].push({
                                        "元素名称": item.elementName,
                                        "Aclid": item.elementAclId
                                    })
                                })
                                BcExportExcel({sheetData,sheetList,name: data.name})
                            } else {
                                // 多tab页
                                var sheetData = [],
                                    sheetList = []
                                res.data.forEach((item,index) => {
                                    sheetData.push([])
                                    sheetList.push(item.elementName)
                                    item.elementChildList.forEach(sitem => {
                                        sheetData[index].push({
                                            "元素名称": sitem.elementName,
                                            "Aclid": sitem.elementAclId
                                        })
                                    })
                                })
                                BcExportExcel({sheetData,sheetList,name: data.name})
                            }
                    	} else {
                    	    this.$message.error('当前菜单没有需要导出的元素')
                    	}

                    })
	            }
			}
        }
	};
</script>

<style scoped lang="scss">
.container{
  padding-left: 12px;
}
	/* reset */
	/deep/ .el-textarea__inner {
		height: 100%;
	}

	/* reset end */

	/* add-plat-btn */
	.add-plat-btn {
		margin-bottom: 15px;
	}

	/* add-plat-btn end */
	/* tree */
	.tree {
		padding: 12px;
		box-shadow: 0px 0px 6px 1px rgba(0, 0, 0, .1);
		background: #fff;
		.custom-tree-node {
			font-size: 14px;
		}

		.tree-btn {
			width: 16px;
			height: 16px;
			line-height: 16px;
			text-align: center;
			display: inline-block;
			font-size: 16px;
		}

		.tree-btn-add {
			background: #f0f9eb;
			color: #67c23a;
		}

		.tree-btn-edit {
			background: #fdf6ec;
			color: #e6a23c;
		}

		.tree-btn-remove {
			background: #fef0f0;
			color: #f56c6c;
		}

		.tree-btn-download {
			background: #ecf5ff;
			color: #409eff;
		}

		/deep/ .is-current {
			> .el-tree-node__content {
				background: #ecf5ff;

				.txt {
					color: #409eff;
				}
			}
		}
	}

	/* tree end */
	/* addMenuDialog */
	.addMenuDialog {
		/deep/ .el-dialog {
			margin: 50px auto !important;
		}
	}

	/* addMenuDialog end */
	/* single-element */
	.single-element {
		padding: 20px;
		min-height: 400px;
		box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1)
	}

	/* single-element end */
	/* multiple-element */
	.multiple-element {
		.tabs {
			/deep/ .el-tabs__nav-scroll {
				height: 39px;
			}

			/deep/ .el-tabs__new-tab {
				margin-right: 10px;
				color: #fff;
				background-color: #409eff;
				border-color: #409eff;
			}
		}
	}
	.element-tag-box {
		margin-top: 10px;
		.element-tag {
			margin-right: 4px;
			margin-bottom: 4px;
		}
	}

	/* multiple-element end */
	/* element-form */
	.element-form {
		.form-item {
			padding-right: 40px;
			position: relative
		}

		.circlr-btn {
			position: absolute;
			right: -40px;
			top: 0;
		}
	}

	/* element-form end */
</style>
